# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  def list_records (records, link = true, prefix = "<li>", postfix = "</li>\n")
    return nil unless records and records.instance_of?(Array)
    list = ""
    for rec in records
      list += prefix
      if link
        list += link_to_record(rec) 
      else
        list += rec.name
      end
      list += postfix
    end
    return list
  end
  
  def options_array_select (an_array, selected = "")
    options = "<option value=\"\">Please choose</option>\n"
    if an_array
      an_array.each do |attr|
        options += "<option"
      if attr == selected
        options += " selected=\"selected\""
      end
      options += ">#{attr}</option>\n"
      end
    end
    return options
  end
  
  def options_hash_select (a_hash, selected = "")
    options = "<option value=\"\">Please choose</option>\n"
    if a_hash
      a_hash.sort.each do |key, value|
        options += "<option"
      if key == selected
        options += " selected=\"selected\""
      end
      options += " value=\"#{key}\">#{value}</option>\n"
      end
    end
    return options
  end
  
  def options_records_select (records, selected = 0)
    options = "<option value=\"\">Please select</option>\n"
    if records then
      records.each do |rec|
        options += "<option "
        if selected == rec.id
          options += "selected=\"selected\" "
        end
        name = rec.name
        name = rec.name_and_title unless !rec.instance_of?(Character)
        options += "value=\"#{rec.id}\">#{name}</option>\n"
      end
    end
    return options
  end
  
  def link_to_record (record, return_if_nil="None", name=nil)
    if record
      if record.instance_of?(Character) && name.nil?
        name = record.name_and_title
      end
      name = record.name unless name
      link_to name, record
    else
      return_if_nil
    end
  end
  
  
end
